#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT 9876

int sockfd;

void *thread0(void *param)
{
	char fromServer[BUFSIZ];
	while (read(sockfd, fromServer, sizeof(fromServer)) != 0)
	{
		printf("\nFrom Server: %s\n", fromServer);
		memset(fromServer, 0, BUFSIZ);
	}
	puts("Server disconnected, closing client");
	close(sockfd);
	exit(0);
}

int main(int argc, char* argv[])
{
	struct sockaddr_in serv_addr;
	char toServer[BUFSIZ];
	pthread_t thread;

	if (argc != 2)
	{
		fprintf(stderr, "Correct usage: %s Address\n", argv[0]);
		exit(-1);
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		fprintf(stderr, "Socket returned null\n");
		exit(-2);
	}

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

	if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
	{
		fputs("Connection error\n", stderr);
		exit(-3);
	}

	pthread_create(&thread, NULL, thread0, 0);

	while (1)
	{
		fgets(toServer, sizeof(toServer), stdin);
		write(sockfd, toServer, strlen(toServer));
		printf("To Server: %s\n", toServer);
	}
}

